﻿// Open Source: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Project: YoProgramo.NET (http://code.google.com/p/yoprogramo/)
// Autor: Fabian Figueredo (info@fabianfigueredo.com.ar)
// Blog: blog.yoprogramo.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.ServiceLocation;
using YoProgramo.Domain.BusinessLogic.Extensions;
using YoProgramo.Domain.BusinessLogic.Service;
using YoProgramo.Domain.Core.Exceptions;
using YoProgramo.Infrastructure.Tools.Markdown;
using YoProgramo.Domain.Core.Entities;
using YoProgramo.Domain.Core.Interfaces;

namespace YoProgramo.Domain.BusinessLogic.Binders
{
    public class StoryBinder : IModelBinder {

        public StoryBinder()
        {
            _userrepository = ServiceLocator.Current.GetInstance<IUserRepository>();
            _storyrepository = ServiceLocator.Current.GetInstance<IStoryRepository>();
            _categoryrepository = ServiceLocator.Current.GetInstance<ICategoryRepository>();
            _tagrepository = ServiceLocator.Current.GetInstance<ITagRepository>();            
            _tagService = ServiceLocator.Current.GetInstance<ITagService>();
            
        }

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            Markdown markDown = new Markdown();

            HttpContextBase context = controllerContext.HttpContext;

            Story story = (Story)(context.Request.Form["story.Id"] != null ? _storyrepository.Get(int.Parse(context.Request.Form["story.Id"])) : new Story());
            story.Title = context.Request.Form["story.Title"];

            // Markdown Format
            story.TextBody = context.Request.Form["story.TextBody"];

            // Html Format
            story.HtmlBody = ExtraTools.Sanitize(markDown.Transform(story.TextBody));

            if (!string.IsNullOrEmpty(context.Request.Form["story.Category"]))
            {
                story.Category = _categoryrepository.Get(long.Parse(context.Request.Form["story.Category"]));
            }

            if (!string.IsNullOrEmpty(context.Request.Form["story.Tags"]))
            {
                story.Tags = SplitAndConvertTags(context.Request.Form["story.Tags"]);
            }

            if (!string.IsNullOrEmpty(context.Request.Form["story.UserName"]))
                story.ByUser = _userrepository.FindByUserName(context.Request.Form["story.UserName"]);
                        
            return story;
        }

        private IList<Tag> SplitAndConvertTags(string s_tags)
        {            
            s_tags = s_tags.ToLower().Trim();
            var tags_words = (IList<string>)s_tags.Split(new char[] { ',' }).ToList();
            IList<Tag> tags = new List<Tag>();

            var tagService = ServiceLocator.Current.GetInstance<ITagService>();
            foreach (string s in tags_words)
            {
                Tag t = (Tag) _tagrepository.FindByName(s.Trim());
                if(t == null)
                {
                    t = new Tag();
                    t.Name = s.Trim();

                    string slug = ExtraTools.GenerateSlug(t.Name);
                    if (slug.Length < 1 || tagService.GetBySlug(slug) != null)
                        throw new YPException("Un error ocurrió al crear slug");

                    t.Slug = slug;
                    _tagService.Create(t);
                }
                tags.Add(t);
            }

            return tags;
        }

        private IStoryRepository _storyrepository;
        private IUserRepository _userrepository;
        private ICategoryRepository _categoryrepository;
        private ITagRepository _tagrepository;
        private ITagService _tagService;
    }
}